var UPLOAD_OPTION,DOMAIN = 'http://res1.hubcloud.com.cn';
function fileUpload(obj) {
    if(!UPLOAD_OPTION) {
        $.ajax({
            url: DOMAIN + "/fileUp/getUpInfo",
            type:"post",
            dataType: "json",
            data: {
                "project": 0,   // 项目,   0代表dsp， 1代表adx
                "funcUrl": obj.funcUrl    //功能， 0代表ad， 1代表oem， 2代表clientInfo
            },
            success: function (data) {
                UPLOAD_OPTION = {
                    upKey: data.data.upKey,
                    dir: data.data.dir,
                    funcUrl: data.data.funcUrl,
                    // status: data.status
                    status: 0
                };
                if(UPLOAD_OPTION.status != -1) {
                    uploadStatic(obj);
                } else {
                    uploadQiNiu(obj);
                }
            }
        });
    } else {
        if(UPLOAD_OPTION.status != -1) {
            uploadStatic(obj);
        } else {
            uploadQiNiu(obj);
        }
    }
    
    // 文件上传到本地服务器
    function uploadStatic(option) {
        // 保证id唯一
        var iptID = 'uploadInput'+ (new Date()).getTime;
        var xhr = this.xhr = new XMLHttpRequest();
        var input = document.createElement('input');
        input.setAttribute('id', iptID);
        input.setAttribute('type', 'file');
        input.setAttribute('name', 'file');
        document.body.appendChild(input);
        input.style.display = 'none';
        this.input = input;
        if(option.btnId) {
            $(document).off("click","#"+option.btnId).on("click","#"+option.btnId,function(){
                input.click();
            })
        }

        input.onchange = function(){
            var fd = new FormData();
            // 模拟七牛的up对象
            var up = {
                file: [],
                removeFile: function(file){
                    var index = Array.prototype.indexOf.call(input.files,file.nFile);
                    if(index != -1) {
                        up.file.splice(index,1);
                    }
                }
            }
            for(var i = 0; i < input.files.length; i++) {
                up.file.push(input.files[i])
            }
            if(!input.value){return;}
            if(option.maxSize &&  input.files[0].size > option.maxSize * 1024 * 1024){
                alert('请上传小于'+option.maxSize+'M的文件');
                return;
            }
            if(option.BeforeUpload instanceof Function){
                for(var i = 0; i < input.files.length; i++) {
                    // 模拟七牛file对象
                    var file = {
                        nFile: input.files[i],
                        name: input.files[i].name,
                        size: input.files[i].size,
                        getNative: function(){ return this.nFile; }
                    }
                    option.BeforeUpload(up,file,next)
                }
            } else {
                next()
            }
            // 结束后清空input
            input.value = "";
            function next() {
                if(up.file.length == 0) {return;}
                if(option.preview instanceof Function) {
                    var preArr = []
                        nameReg = /(\.jpe?g)|(\.png)|(\.gif)|(\.mp4)$/;
                    for(var i = 0; i < up.file.length; i++) {
                        var file = up.file[i];
                        if(nameReg.test(file.name)){
                            preArr.push(getObjectURL(file))
                        } else {
                            preArr.push("");
                        }
                    }
                    option.preview(preArr)
                }
                fd.append('file', up.file[0]);
                // fd.append('dir', UPLOAD_OPTION.dir);
                // fd.append('upKey', UPLOAD_OPTION.upKey);
                xhr.open('post', DOMAIN + '/fileUp/upload/'+UPLOAD_OPTION.dir+'/'+UPLOAD_OPTION.funcUrl+'/'+UPLOAD_OPTION.upKey);
                xhr.onreadystatechange = function(){
                    if(xhr.readyState == 4){
                        if(xhr.status == 200){
                            var res = JSON.parse(xhr.responseText);
                            if(res.status != -1) {
                                option.FileUploaded && option.FileUploaded(res.data,option.index);
                            } else {
                                option.Error && option.Error();
                            }
                            input.value = "";
                        } else if(xhr.status != 0){
                            alert("上传失败")
                        }
                    }
                }
                xhr.upload.onprogress = function(event){
                    var pre = Math.floor(100 * event.loaded / event.total);
                    option.UploadProgress && option.UploadProgress(pre,option.index);
                }
                xhr.send(fd);
            }
        }
        function getObjectURL(file) {
            var url = null ;
            if (window.createObjectURL!=undefined) { // basic
                url = window.createObjectURL(file) ;
            } else if (window.URL!=undefined) { // mozilla(firefox)
                url = window.URL.createObjectURL(file) ;
            } else if (window.webkitURL!=undefined) { // webkit or chrome
                url = window.webkitURL.createObjectURL(file) ;
            }
            return url ;
        }
    }
    // uploadStatic.prototype.upload = function() {
    //     this.input.click();
    // }


    //  文件上传到七牛
    function uploadQiNiu(obj) {
        $.ajax({
            url: STATIC_URL["domian"]+"/dsp/qiniu/token",
            type:"post",
            dataType: "json",
            data:JSON.stringify({'token':token}),
            success: function (data) {
                if (data.status != "1") {
                    var uptoken = data.data.token;
                    var domain = data.data.baseUrl;
                    options(uptoken, domain, obj);
                } else {

                }
            }
        });
        function options(uptoken, domain ,obj) {
            Qiniu.tokenInfo = {isExpired: function () {return true;}};
            var uploader = Qiniu.uploader({
                runtimes: 'html5,flash,html4',
                browse_button: obj.btnId,
                uptoken: uptoken,
                domain: domain,
                get_new_uptoken: false,
                container: 'container',
                max_file_size: '100mb',
                flash_swf_url: 'js/plupload/Moxie.swf',
                max_retries: 3,
                dragdrop: true,
                drop_element: (obj.dragUpload || "container"),
                chunk_size: '4mb',
                auto_start: true,
                unique_names: true,

                init: {
                    'FilesAdded': function(up, files) {
                        plupload.each(files, function(file) {
                            obj.FilesAdded && obj.FilesAdded(up, file, obj.index);
                        });
                    },
                    'BeforeUpload': function(up, file) {
                        obj.BeforeUpload && obj.BeforeUpload(up, file, obj.index);
                    },
                    'UploadProgress': function(up, file) {
                        obj.UploadProgress && obj.UploadProgress(file.percent, obj.index);
                    },
                    'FileUploaded': function(up, file, info) {
                        info = JSON.parse(info);
                        var reInfo = {
                            url : domain + info.key,
                            size : info.fsize,
                            w : info.w,
                            h : info.h,
                            type : file.type,
                            md5: info.hash,
                            name: file.name
                        };
                        obj.FileUploaded && obj.FileUploaded(reInfo, obj.index);
                    },
                    'Error': function(up, err, errTip) {
                        obj.Error && obj.Error(up, file);
                    },
                    'UploadComplete': function() {
                        obj.UploadComplete && obj.UploadComplete(up, file);
                    },
                    'Key': function(up, file) {
                        obj.Key && obj.Key(up, file);
                    }
                }
            });
        }
    }
}